'use client';

import { useState, useEffect } from 'react';
import Sidebar from '@/components/Sidebar';
import { HistoryItem, Category, STORAGE_KEYS, DEFAULT_CATEGORIES } from '@/types';

const PARSE_APIS = [
  {
    name: '接口1',
    url: 'https://jx.xmflv.com/?url=',
  },
  {
    name: '接口2',
    url: 'https://jx.parwix.com:4433/player/?url=',
  },
  {
    name: '接口3',
    url: 'https://jx.iztyy.com/svip/?url=',
  },
  {
    name: '接口4',
    url: 'https://jx.bozrc.com:4433/player/?url=',
  },
  {
    name: '接口5',
    url: 'https://jx.4kdv.com/?url=',
  }
];

export default function History() {
  const [history, setHistory] = useState<HistoryItem[]>([]);
  const [darkMode, setDarkMode] = useState(false);
  const [currentApiIndex, setCurrentApiIndex] = useState(0);
  const [searchTerm, setSearchTerm] = useState('');
  const [username, setUsername] = useState('用户');
  const [editingTitleIndex, setEditingTitleIndex] = useState<number | null>(null);
  const [tempTitle, setTempTitle] = useState('');
  const [editingDescIndex, setEditingDescIndex] = useState<number | null>(null);
  const [tempDescription, setTempDescription] = useState('');
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [categories, setCategories] = useState<Category[]>([]);
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  const [editingCategoryIndex, setEditingCategoryIndex] = useState<number | null>(null);
  const [tempCategory, setTempCategory] = useState<string | null>(null);

  // 初始化主题
  useEffect(() => {
    // 检查本地存储的主题设置
    const savedTheme = localStorage.getItem('theme');
    const prefersColorScheme = window.matchMedia('(prefers-color-scheme: dark)');
    const systemPrefersDark = prefersColorScheme.matches;

    // 根据保存的设置或系统偏好设置主题
    if (savedTheme === 'light') {
      // 用户明确设置为亮色
      setDarkMode(false);
      document.documentElement.classList.remove('dark');
    } else if (savedTheme === 'dark') {
      // 用户明确设置为暗色
      setDarkMode(true);
      document.documentElement.classList.add('dark');
    } else {
      // 没有保存过主题，根据系统偏好设置
      setDarkMode(systemPrefersDark);
      if (systemPrefersDark) {
        document.documentElement.classList.add('dark');
        localStorage.setItem('theme', 'dark');
      } else {
        document.documentElement.classList.remove('dark');
        localStorage.setItem('theme', 'light');
      }
    }

    // 监听主题变化事件（从其他页面触发的）
    const handleThemeChange = (e: CustomEvent) => {
      const newTheme = e.detail.theme;
      setDarkMode(newTheme === 'dark');
      if (newTheme === 'dark') {
        document.documentElement.classList.add('dark');
      } else {
        document.documentElement.classList.remove('dark');
      }
    };

    window.addEventListener('themeChange', handleThemeChange as EventListener);
    
    // 加载历史记录
    const savedHistory = localStorage.getItem(STORAGE_KEYS.HISTORY);
    if (savedHistory) {
      setHistory(JSON.parse(savedHistory));
    }

    // 加载分类
    const savedCategories = localStorage.getItem(STORAGE_KEYS.CATEGORIES);
    if (savedCategories) {
      setCategories(JSON.parse(savedCategories));
    } else {
      // 如果没有保存的分类，使用默认分类
      setCategories(DEFAULT_CATEGORIES);
      localStorage.setItem(STORAGE_KEYS.CATEGORIES, JSON.stringify(DEFAULT_CATEGORIES));
    }

    // 加载当前接口索引
    const savedApiIndex = localStorage.getItem(STORAGE_KEYS.API_INDEX);
    if (savedApiIndex) {
      setCurrentApiIndex(parseInt(savedApiIndex, 10));
    }

    // 加载用户名
    const savedUsername = localStorage.getItem(STORAGE_KEYS.USERNAME);
    if (savedUsername) {
      setUsername(savedUsername);
    }
    
    return () => {
      window.removeEventListener('themeChange', handleThemeChange as EventListener);
    };
  }, []);

  const saveHistory = (newHistory: HistoryItem[]) => {
    setHistory(newHistory);
    localStorage.setItem(STORAGE_KEYS.HISTORY, JSON.stringify(newHistory));
  };
  
  // 处理分类选择
  const handleSelectCategory = (categoryId: string | null) => {
    setSelectedCategory(categoryId);
  };
  
  // 更新历史记录项的分类
  const updateItemCategory = (index: number, categoryId: string | null) => {
    const newHistory = [...history];
    newHistory[index].category = categoryId || undefined;
    saveHistory(newHistory);
    setEditingCategoryIndex(null);
  };

  const toggleFavorite = (index: number) => {
    const newHistory = [...history];
    newHistory[index].isFavorite = !newHistory[index].isFavorite;
    saveHistory(newHistory);
  };

  const removeFromHistory = (index: number) => {
    const newHistory = history.filter((_, i) => i !== index);
    saveHistory(newHistory);
  };

  const clearHistory = () => {
    if (confirm('确定要清空所有历史记录吗？')) {
      saveHistory([]);
    }
  };

  // 处理URL，移除?后的所有参数
  const cleanUrl = (url: string) => {
    try {
      const urlObj = new URL(url);
      return urlObj.origin + urlObj.pathname;
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (error) {
      // 如果不是有效URL，直接返回原始值
      return url;
    }
  };

  const parseVideo = (url: string) => {
    // 清理URL，移除?后的所有参数
    const cleanedUrl = cleanUrl(url);
    const parseUrl = PARSE_APIS[currentApiIndex].url + encodeURIComponent(cleanedUrl);
    window.open(parseUrl, '_blank');
  };

  // 筛选历史记录 - 仅应用搜索筛选，移除分类筛选
  const filteredHistory = history.filter(item => {
    // 搜索条件
    return item.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.url.toLowerCase().includes(searchTerm.toLowerCase());
  });
  
  // 获取分类名称
  const getCategoryName = (categoryId: string | undefined) => {
    if (!categoryId) return null;
    const category = categories.find(c => c.id === categoryId);
    return category ? category : null;
  };

  // 开始编辑视频标题
  const startEditTitle = (index: number, currentTitle: string) => {
    setEditingTitleIndex(index);
    setTempTitle(currentTitle);
  };

  // 保存视频标题
  const saveTitle = (index: number) => {
    if (tempTitle.trim()) {
      const newHistory = [...history];
      newHistory[index].title = tempTitle.trim();
      saveHistory(newHistory);
    }
    setEditingTitleIndex(null);
  };

  // 取消编辑标题
  const cancelEditTitle = () => {
    setEditingTitleIndex(null);
  };

  // 开始编辑描述
  const startEditDescription = (index: number, currentDescription: string = '') => {
    setEditingDescIndex(index);
    setTempDescription(currentDescription);
  };

  // 保存描述
  const saveDescription = (index: number) => {
    const newHistory = [...history];
    newHistory[index].description = tempDescription.trim() || undefined;
    saveHistory(newHistory);
    setEditingDescIndex(null);
  };

  // 取消编辑描述
  const cancelEditDescription = () => {
    setEditingDescIndex(null);
  };

  // 开始编辑分类
  const startEditCategory = (index: number) => {
    setEditingCategoryIndex(index);
    setTempCategory(history[index].category || null);
  };

  return (
    <div className="flex h-full">
      {/* 侧边栏 */}
      <Sidebar 
        darkMode={darkMode} 
        username={username} 
        isOpen={sidebarOpen} 
        onToggle={() => setSidebarOpen(!sidebarOpen)} 
      />
      
      {/* 主内容区 */}
      <div className={`flex-1 md:ml-64 bg-white dark:bg-black min-h-screen text-black dark:text-white transition-all duration-300 ${
        sidebarOpen ? 'md:translate-x-0' : 'translate-x-0'
      }`}>
        {/* 顶部导航 */}
        <nav className="border-b border-gray-100 dark:border-gray-800">
          <div className="max-w-5xl mx-auto px-4 py-4 flex justify-between items-center">
            <div className="flex items-center">
              {/* 移动端汉堡菜单按钮 */}
              <button
                className="md:hidden mr-4 text-gray-600 dark:text-gray-400"
                onClick={() => setSidebarOpen(!sidebarOpen)}
                aria-label="打开菜单"
              >
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-6 h-6">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" />
                </svg>
              </button>
              <h1 className="text-xl font-medium">历史记录</h1>
            </div>
            <div className="text-sm text-gray-500 dark:text-gray-400">
              当前接口: {PARSE_APIS[currentApiIndex].name}
            </div>
          </div>
        </nav>

        <main className="max-w-5xl mx-auto px-4 py-8">
          {/* 搜索和操作栏 */}
          <div className="mb-8">
            <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-4">
              <div className="relative w-full sm:max-w-md">
                <input
                  type="text"
                  placeholder="搜索历史记录..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="w-full py-2 px-3 pr-10 border border-gray-200 dark:border-gray-800 rounded-lg bg-white dark:bg-black focus:outline-none focus:ring-1 focus:ring-gray-400 dark:focus:ring-gray-500"
                />
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  fill="none"
                  viewBox="0 0 24 24"
                  strokeWidth={1.5}
                  stroke="currentColor"
                  className="w-5 h-5 absolute right-3 top-1/2 -translate-y-1/2 text-gray-400"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z"
                  />
                </svg>
              </div>
              <button
                onClick={clearHistory}
                className="py-2 px-4 border border-red-200 text-red-500 hover:bg-red-50 dark:border-red-900 dark:hover:bg-red-900/10 rounded-lg flex items-center"
              >
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-4 h-4 mr-1">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" />
                </svg>
                清空历史
              </button>
            </div>
          </div>

          {/* 历史记录列表 */}
          <div className="space-y-4">
            {filteredHistory.length === 0 ? (
              <div className="py-12 text-center text-gray-400 dark:text-gray-500">
                {searchTerm ? '没有找到匹配的记录' : '暂无历史记录'}
              </div>
            ) : (
              filteredHistory.map((item, index) => (
                <div key={index} className="p-4 bg-white dark:bg-gray-900 border border-gray-100 dark:border-gray-800 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors">
                  <div className="flex flex-col md:flex-row md:justify-between md:items-start gap-3">
                    <div className="flex-1 min-w-0 relative">
                      {/* 操作按钮 - 仅在移动端显示为右下角水平排列 */}
                      <div className="md:hidden flex items-center space-x-2 text-gray-400 dark:text-gray-500 absolute bottom-0 right-0 pb-1">
                        <button
                          onClick={() => parseVideo(item.url)}
                          className="p-2 hover:text-blue-500 transition-colors"
                          title="解析视频"
                        >
                          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
                            <path strokeLinecap="round" strokeLinejoin="round" d="m15.75 10.5 4.72-4.72a.75.75 0 0 1 1.28.53v11.38a.75.75 0 0 1-1.28.53l-4.72-4.72M4.5 18.75h9a2.25 2.25 0 0 0 2.25-2.25v-9a2.25 2.25 0 0 0-2.25-2.25h-9A2.25 2.25 0 0 0 2.25 7.5v9a2.25 2.25 0 0 0 2.25 2.25Z" />
                          </svg>
                        </button>
                        <button
                          onClick={() => toggleFavorite(index)}
                          className={`p-2 ${item.isFavorite ? 'text-yellow-400 hover:text-yellow-500' : 'hover:text-yellow-400'} transition-colors`}
                          title={item.isFavorite ? '取消收藏' : '添加收藏'}
                        >
                          {item.isFavorite ? (
                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="w-5 h-5">
                              <path fillRule="evenodd" d="M10.788 3.21c.448-1.077 1.976-1.077 2.424 0l2.082 5.007 5.404.433c1.164.093 1.636 1.545.749 2.305l-4.117 3.527 1.257 5.273c.271 1.136-.964 2.033-1.96 1.425L12 18.354 7.373 21.18c-.996.608-2.231-.29-1.96-1.425l1.257-5.273-4.117-3.527c-.887-.76-.415-2.212.749-2.305l5.404-.433 2.082-5.006z" clipRule="evenodd" />
                            </svg>
                          ) : (
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
                              <path strokeLinecap="round" strokeLinejoin="round" d="M11.48 3.499a.562.562 0 0 1 1.04 0l2.125 5.111a.563.563 0 0 0 .475.345l5.518.442c.499.04.701.663.321.988l-4.204 3.602a.563.563 0 0 0-.182.557l1.285 5.385a.562.562 0 0 1-.84.61l-4.725-2.885a.562.562 0 0 0-.586 0L6.982 20.54a.562.562 0 0 1-.84-.61l1.285-5.386a.562.562 0 0 0-.182-.557l-4.204-3.602a.563.563 0 0 1 .321-.988l5.518-.442a.563.563 0 0 0 .475-.345L11.48 3.5Z" />
                            </svg>
                          )}
                        </button>
                        <button 
                          onClick={() => removeFromHistory(index)}
                          className="p-2 hover:text-red-500 transition-colors"
                          title="删除记录"
                        >
                          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
                            <path strokeLinecap="round" strokeLinejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" />
                          </svg>
                        </button>
                      </div>
                      
                      {editingTitleIndex === index ? (
                        <div className="flex flex-wrap items-center gap-2 mb-1">
                          <input
                            type="text"
                            value={tempTitle}
                            onChange={(e) => setTempTitle(e.target.value)}
                            className="px-2 py-1 text-base border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-black dark:text-white w-full md:w-64"
                            maxLength={50}
                            autoFocus
                          />
                          <div className="flex items-center">
                            <button
                              onClick={() => saveTitle(index)}
                              className="p-1 text-green-600 dark:text-green-400"
                              title="保存"
                            >
                              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12.75l6 6 9-13.5" />
                              </svg>
                            </button>
                            <button
                              onClick={cancelEditTitle}
                              className="p-1 text-red-600 dark:text-red-400"
                              title="取消"
                            >
                              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                              </svg>
                            </button>
                          </div>
                        </div>
                      ) : (
                        <div className="flex items-center gap-2 mb-1 flex-wrap">
                          <p className="font-medium text-lg break-all">{item.title}</p>
                          <button
                            onClick={() => startEditTitle(index, item.title)}
                            className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 shrink-0"
                            title="修改名称"
                          >
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-4 h-4">
                              <path strokeLinecap="round" strokeLinejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10" />
                            </svg>
                          </button>
                          
                          {/* 桌面端操作按钮 */}
                          <div className="hidden md:flex ml-auto space-x-2 text-gray-400 dark:text-gray-500">
                            <button
                              onClick={() => parseVideo(item.url)}
                              className="p-2 hover:text-blue-500 transition-colors"
                              title="解析视频"
                            >
                              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
                                <path strokeLinecap="round" strokeLinejoin="round" d="m15.75 10.5 4.72-4.72a.75.75 0 0 1 1.28.53v11.38a.75.75 0 0 1-1.28.53l-4.72-4.72M4.5 18.75h9a2.25 2.25 0 0 0 2.25-2.25v-9a2.25 2.25 0 0 0-2.25-2.25h-9A2.25 2.25 0 0 0 2.25 7.5v9a2.25 2.25 0 0 0 2.25 2.25Z" />
                              </svg>
                            </button>
                            <button
                              onClick={() => toggleFavorite(index)}
                              className={`p-2 ${item.isFavorite ? 'text-yellow-400 hover:text-yellow-500' : 'hover:text-yellow-400'} transition-colors`}
                              title={item.isFavorite ? '取消收藏' : '添加收藏'}
                            >
                              {item.isFavorite ? (
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="w-5 h-5">
                                  <path fillRule="evenodd" d="M10.788 3.21c.448-1.077 1.976-1.077 2.424 0l2.082 5.007 5.404.433c1.164.093 1.636 1.545.749 2.305l-4.117 3.527 1.257 5.273c.271 1.136-.964 2.033-1.96 1.425L12 18.354 7.373 21.18c-.996.608-2.231-.29-1.96-1.425l1.257-5.273-4.117-3.527c-.887-.76-.415-2.212.749-2.305l5.404-.433 2.082-5.006z" clipRule="evenodd" />
                                </svg>
                              ) : (
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
                                  <path strokeLinecap="round" strokeLinejoin="round" d="M11.48 3.499a.562.562 0 0 1 1.04 0l2.125 5.111a.563.563 0 0 0 .475.345l5.518.442c.499.04.701.663.321.988l-4.204 3.602a.563.563 0 0 0-.182.557l1.285 5.385a.562.562 0 0 1-.84.61l-4.725-2.885a.562.562 0 0 0-.586 0L6.982 20.54a.562.562 0 0 1-.84-.61l1.285-5.386a.562.562 0 0 0-.182-.557l-4.204-3.602a.563.563 0 0 1 .321-.988l5.518-.442a.563.563 0 0 0 .475-.345L11.48 3.5Z" />
                                </svg>
                              )}
                            </button>
                            <button
                              onClick={() => removeFromHistory(index)}
                              className="p-2 hover:text-red-500 transition-colors"
                              title="删除记录"
                            >
                              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" />
                              </svg>
                            </button>
                          </div>
                        </div>
                      )}
                      
                      {/* 分类标签 */}
                      {item.category ? (
                        <div className="flex items-center gap-2 mt-1">
                          {(() => {
                            const category = getCategoryName(item.category);
                            return category ? (
                              <div 
                                className="px-2 py-0.5 text-xs rounded-full text-white" 
                                style={{ backgroundColor: category.color }}
                              >
                                {category.name}
                              </div>
                            ) : null;
                          })()}
                          <button
                            onClick={() => startEditCategory(index)}
                            className="text-xs text-blue-500 hover:underline"
                          >
                            更改
                          </button>
                        </div>
                      ) : (
                        <button
                          onClick={() => startEditCategory(index)}
                          className="text-xs text-blue-500 hover:underline flex items-center mt-1"
                        >
                          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-4 h-4 mr-1">
                            <path strokeLinecap="round" strokeLinejoin="round" d="M9.568 3H5.25A2.25 2.25 0 0 0 3 5.25v4.318c0 .597.237 1.17.659 1.591l9.581 9.581c.699.699 1.78.872 2.607.33a18.095 18.095 0 0 0 5.223-5.223c.542-.827.369-1.908-.33-2.607L11.16 3.66A2.25 2.25 0 0 0 9.568 3Z" />
                            <path strokeLinecap="round" strokeLinejoin="round" d="M6 6h.008v.008H6V6Z" />
                          </svg>
                          添加分类
                        </button>
                      )}
                      
                      {/* 分类选择弹窗 */}
                      {editingCategoryIndex === index && (
                        <div className="mt-2 p-2 bg-gray-50 dark:bg-gray-800 rounded border border-gray-200 dark:border-gray-700">
                          <div className="flex flex-wrap gap-2 mb-2">
                            {categories.map(category => (
                              <button
                                key={category.id}
                                onClick={() => updateItemCategory(index, category.id)}
                                className="flex items-center gap-1 px-2 py-1 rounded text-xs hover:bg-gray-100 dark:hover:bg-gray-700"
                              >
                                <span 
                                  className="w-3 h-3 rounded-full" 
                                  style={{ backgroundColor: category.color }}
                                />
                                {category.name}
                              </button>
                            ))}
                            <button
                              onClick={() => updateItemCategory(index, null)}
                              className="px-2 py-1 rounded text-xs hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-500"
                            >
                              无分类
                            </button>
                          </div>
                          <button
                            onClick={() => setEditingCategoryIndex(null)}
                            className="text-xs text-gray-500 hover:underline"
                          >
                            取消
                          </button>
                        </div>
                      )}
                      
                      <p className="text-sm text-gray-500 dark:text-gray-400 mb-2 break-all">
                        {item.url}
                      </p>
                      
                      {/* 视频简介 */}
                      {editingDescIndex === index ? (
                        <div className="mb-2">
                          <textarea
                            value={tempDescription}
                            onChange={(e) => setTempDescription(e.target.value)}
                            className="w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-black dark:text-white"
                            placeholder="添加视频简介..."
                            rows={3}
                            maxLength={200}
                          />
                          <div className="flex items-center gap-2 mt-1">
                            <button
                              onClick={() => saveDescription(index)}
                              className="p-1 text-xs text-green-600 dark:text-green-400 flex items-center"
                              title="保存"
                            >
                              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-4 h-4 mr-1">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12.75l6 6 9-13.5" />
                              </svg>
                              保存
                            </button>
                            <button
                              onClick={cancelEditDescription}
                              className="p-1 text-xs text-red-600 dark:text-red-400 flex items-center"
                              title="取消"
                            >
                              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-4 h-4 mr-1">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                              </svg>
                              取消
                            </button>
                          </div>
                        </div>
                      ) : (
                        <div className="mb-2">
                          {item.description ? (
                            <div className="text-sm text-gray-700 dark:text-gray-300 bg-gray-50 dark:bg-gray-850 p-2 rounded border border-gray-100 dark:border-gray-800">
                              {item.description}
                              <button
                                onClick={() => startEditDescription(index, item.description)}
                                className="ml-2 text-xs text-blue-500 hover:underline"
                                title="编辑简介"
                              >
                                编辑
                              </button>
                            </div>
                          ) : (
                            <button
                              onClick={() => startEditDescription(index)}
                              className="text-xs text-blue-500 hover:underline flex items-center"
                            >
                              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-4 h-4 mr-1">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
                              </svg>
                              添加简介
                            </button>
                          )}
                        </div>
                      )}
                      
                      <p className="text-xs text-gray-400 dark:text-gray-500 md:text-right pr-24 md:pr-0">
                        {new Date(item.timestamp).toLocaleString()}
                      </p>
                    </div>
                  </div>
                </div>
              ))
            )}
          </div>
        </main>
        
        {/* 页脚 */}
        <footer className="border-t border-gray-100 dark:border-gray-800 py-6 mt-12">
          <div className="max-w-5xl mx-auto px-4 text-center text-sm text-gray-500 dark:text-gray-400">
            <p>本工具仅用于学习和研究，请勿用于非法用途</p>
          </div>
        </footer>
      </div>
    </div>
  );
} 